package com.gomore.opple.module.main.shoppingcar;

import com.gomore.opple.common.GlobalConstant;
import com.gomore.opple.data.DataRepository;
import com.gomore.opple.data.remote.retrofit.HttpResponseFunc;
import com.gomore.opple.data.remote.retrofit.RxSubscriber;
import com.gomore.opple.data.remote.retrofit.ServerResponseFunc;
import com.gomore.opple.exception.ApiException;
import com.gomore.opple.model.EventShoppingCarNumber;
import com.gomore.opple.rest.common.DataPage;
import com.gomore.opple.rest.employee.LoginResult;
import com.gomore.opple.rest.shopcart.DeleteCartRequest;
import com.gomore.opple.rest.shopcart.ShopCartFilter;
import com.gomore.opple.rest.shopcart.ShopCartResponse;
import com.gomore.opple.web.cgform.consumer.entity.TOConsumerEntity;
import com.gomore.opple.web.cgform.goods.view.VOResellerGoodsEntity;
import com.gomore.opple.web.cgform.shopcart.entity.TOShopcartEntity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import de.greenrobot.event.EventBus;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Created by asus on 2016/12/27.
 */
public class ShoppingCarPresenter implements ShoppingCarContract.Presenter {
    private DataRepository mDataRepositroy;
    private final ShoppingCarContract.View mView;
    private CompositeSubscription mSubscriptions;
    private List<TOShopcartEntity> toShopcartEntityList = new ArrayList<>();
    private int rows = 999;
    private int page = GlobalConstant.PAGE_START;

    @Inject
    ShoppingCarPresenter(DataRepository dataRepository, ShoppingCarContract.View view) {
        mDataRepositroy = dataRepository;
        mView = view;
        mSubscriptions = new CompositeSubscription();
        mView.setPresenter(this);
    }

    @Override
    public void prepareInitData() {

    }

    @Override
    public void queryShoppingCar(String consumerId) {
        mView.showProgressDialog();
        ShopCartFilter shopCartFilter = new ShopCartFilter();
        shopCartFilter.setConsumerId(consumerId);
        DataPage dataPage = new DataPage();
        dataPage.setRows(rows);
        dataPage.setPage(page);
        shopCartFilter.setDp(dataPage);
        mSubscriptions.clear();
        toShopcartEntityList.clear();
        Subscription subscription = mDataRepositroy.queryShoppingCar(shopCartFilter)
                .map(new ServerResponseFunc<ShopCartResponse>())
                .onErrorResumeNext(new HttpResponseFunc<ShopCartResponse>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<ShopCartResponse>() {
                    @Override
                    public void onNext(ShopCartResponse shopCartResponse) {
                        super.onNext(shopCartResponse);
                        mView.hideProgressDialog();
                        toShopcartEntityList.addAll(shopCartResponse.getShopcart());
                        //t添加成交价
                        addCostPrice(toShopcartEntityList);
                        //更新购物车的数量
                        EventShoppingCarNumber eventShoppingCarNumber = new EventShoppingCarNumber();
                        eventShoppingCarNumber.setGetShoppingCarNumber(true);
                        EventBus.getDefault().post(eventShoppingCarNumber);
                        //初始合计
                        mView.showContentView();
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        mView.hideProgressDialog();
                        mView.showMessage(ex.message);
                    }
                });
        mSubscriptions.add(subscription);
    }

    @Override
    public List<TOShopcartEntity> getShoppingCarData() {
        return toShopcartEntityList;
    }

    @Override
    public TOConsumerEntity getConsumer() {
        return mDataRepositroy.getConsumer();
    }

    @Override
    public LoginResult getUser() {
        return mDataRepositroy.getUser();
    }

    @Override
    public void getTotal(List<TOShopcartEntity> toShopcartEntities, HashMap<Integer, Boolean> isSelected) {
        BigDecimal total = new BigDecimal(0);
        int shoppingCarNumber = 0;
        for (int i = 0; i < toShopcartEntities.size(); i++) {
            if (isSelected.get(i)) {
                if (toShopcartEntities.get(i) != null && toShopcartEntities.get(i).getGoodsNum() != null &&
                        toShopcartEntities.get(i).getCostPrice() != null) {
                    BigDecimal mul = toShopcartEntities.get(i).getCostPrice().multiply(new BigDecimal(toShopcartEntities.get(i).getGoodsNum()));
                    total = total.add(mul);
                    shoppingCarNumber = shoppingCarNumber + toShopcartEntities.get(i).getGoodsNum();
                }
            }
        }
        mView.showTotal(total, shoppingCarNumber, false);
    }

    @Override
    public void updateCostPrice(String cartId, String costPrice, String goodsId, String goodsNum, final boolean isReflashShoppingCar) {
        mSubscriptions.clear();
        Subscription subscription = mDataRepositroy.updateCostPrice(cartId, costPrice, goodsId, goodsNum)
                .map(new ServerResponseFunc<String>())
                .onErrorResumeNext(new HttpResponseFunc<String>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<String>() {
                    @Override
                    public void onNext(String String) {
                        super.onNext(String);
                        //刷新购物车数量
                        if (isReflashShoppingCar) {
                            EventShoppingCarNumber eventShoppingCarNumber = new EventShoppingCarNumber();
                            eventShoppingCarNumber.setGetShoppingCarNumber(true);
                            EventBus.getDefault().post(eventShoppingCarNumber);
                        }
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        mView.showMessage(ex.message);
                    }
                });
        mSubscriptions.add(subscription);
    }

    @Override
    public void deleteShoppingCar(List<String> goodIds) {
        mSubscriptions.clear();
        DeleteCartRequest deleteCartRequest = new DeleteCartRequest();
        deleteCartRequest.setCartIds(goodIds);
        Subscription subscription = mDataRepositroy.deleteShoppingCar(deleteCartRequest)
                .map(new ServerResponseFunc<String>())
                .onErrorResumeNext(new HttpResponseFunc<String>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new RxSubscriber<String>() {
                    @Override
                    public void onNext(String String) {
                        super.onNext(String);
                        queryShoppingCar(mDataRepositroy.getConsumer().getId());
                    }

                    @Override
                    protected void onError(ApiException ex) {
                        mView.showMessage(ex.message);
                    }
                });
        mSubscriptions.add(subscription);
    }

    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {
        mSubscriptions.clear();
    }

    /**
     * 添加成交价
     */
    private void addCostPrice(List<TOShopcartEntity> toShopcartEntityList) {
        for (int i = 0; i < toShopcartEntityList.size(); i++) {
            TOShopcartEntity toShopcartEntity = toShopcartEntityList.get(i);
            if (toShopcartEntity.getGoods() == null) {
                continue;
            }
            VOResellerGoodsEntity voResellerGoodsEntity = toShopcartEntity.getGoods();
            //如果成交价为空且吊牌价不为空,则成交价就是吊牌价
            if (voResellerGoodsEntity.getTagPrice() != null) {
                toShopcartEntity.setCostPrice(voResellerGoodsEntity.getTagPrice());
            }
        }
    }
}
